package exams.concurrent;

import java.util.ArrayList;
import java.util.Date;

import static java.lang.Thread.sleep;

public class UnSafeCount {

    private int count = 0;

    public synchronized void increase() {
        count++;
    }

    public synchronized void decrease() {
        count++;
    }

    public int getCount() {
        return this.count;
    }

    public static void main(String[] args) throws InterruptedException {
        int[] tasks = {5,7,11,12,2,1,7,9,11,3};

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (tasks) {
                    try {
                        tasks.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                for(int i=0; i<tasks.length/2; i++) {
                    doTask(tasks[i]);
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (tasks) {
                    tasks.notifyAll();
                }
                for(int i=tasks.length/2; i<tasks.length; i++) {
                    doTask(tasks[i]);
                }
            }
        });

        thread1.start();
        thread1.join(30000);
        thread2.start();
    }

    public static long doTask(int value) {
        long startTime = getCurrentTime();
        try {
            sleep(value * 1000);
            System.out.println("Thread " + Thread.currentThread().getName() + " spent " + value + " done.");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long endTime = getCurrentTime();
        return endTime - startTime;
    }

    public static long getCurrentTime() {
        Date date = new Date();
        return date.getTime();
    }
}